# -*- coding: utf-8 -*-


from functools import lru_cache
from collections import OrderedDict

import py_global
import logging

logger = logging.getLogger(__name__)


@lru_cache(maxsize=5, typed=True)
def get_cache(s: str, i: int):
    """
    缓存算法：最近最少使用
    """
    logger.info(f's:{s},i:{i}.')
    if i == 0 or i == -1:
        return None
    return s * i


def test_lru_cache():
    a = get_cache('-', 3)
    a = get_cache('-', 4)
    a = get_cache('-', 0)
    a = get_cache('-', -1)
    # a = get_cache('-', 0)
    # a = get_cache('-', -1)
    # a = get_cache('-', 5)
    # a = get_cache('-', 9)
    # a = get_cache('-', 7)
    # a = get_cache('-', 0)
    # a = get_cache('-', 5)
    # a = get_cache('-', 3)
    # a = get_cache('-', 1)
    # a = get_cache('-', 3)
    # a = get_cache('-', 0)

    logger.info(get_cache.cache_info())
    get_cache.cache_clear()
    logger.info(get_cache.cache_info())
    pass


class LRUCache(object):
    """
    缓存：最近最少使用
    """

    def __init__(self, capacity):
        self.__capacity = capacity
        self.__ordered_dict = OrderedDict()

    def get(self, key):
        if key not in self.__ordered_dict:
            return None
        value = self.__ordered_dict.get(key)
        self.__ordered_dict.move_to_end(key)  # 使用数据相当于重新插入
        return value

    def put(self, key, value):
        if key in self.__ordered_dict:
            self.__ordered_dict.move_to_end(key)  # 重复数据相当于重新插入
            pass
        else:
            if len(self.__ordered_dict.items()) >= self.__capacity:
                self.__ordered_dict.popitem(last=False)  # 删除最先插入的数据
                pass
            self.__ordered_dict[key] = value
            pass
        pass

    pass


if __name__ == '__main__':
    test_lru_cache()

    # ordered_dict = OrderedDict()
    # ordered_dict['asdf'] = 'asdf'
    # ordered_dict['qwer'] = 'qwer'
    # ordered_dict['1'] = '1'
    # ordered_dict['2'] = '1'
    # ordered_dict['3'] = '1'
    # ordered_dict['4'] = '1'

    pass
